<template>
  <div class="app-container">
    <h1>进店洗</h1>
    <el-form
      :model="formData"
      ref="formData"
      label-width="100px"
      class="order-create-form"
    >
      <el-form-item
        prop="customPhone"
        label="手机号码"
        :rules="[
          { required: true, message: '请输入客户手机电话', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          placeholder="请输入客户手机电话"
          v-model="formData.customPhone"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="选取商品"
        style="margin-bottom: 0"
        prop="orderGoodPoList"
        :rules="[
          {
            required: true,
            type: 'array',
            min: 1,
            message: '商品不能为空',
            trigger: 'blur',
          },
        ]"
      >
        <div
          style="border: 1px solid #eaeaea; border-radius: 6px; padding: 10px"
        >
          <div
            class="choose-product"
            v-for="(product, index) in formData.orderGoodPoList"
          >
            <el-form-item
              :prop="'orderGoodPoList.' + index + '.goodsId'"
              :rules="{
                required: true,
                message: '商品不能为空',
                trigger: 'change',
              }"
            >
              <el-select
                v-model="formData.orderGoodPoList[index].goodsId"
                style="width: 460px"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in productList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              :key="product.key"
              :prop="'orderGoodPoList.' + index + '.buyNum'"
              :rules="[
                {
                  required: true,
                  message: '请输入份数',
                  trigger: 'blur',
                },
                {
                  pattern: /^[1-9]\d*$/,
                  message: '请输入正确的数字',
                  trigger: 'blur',
                },
              ]"
            >
              <el-input
                v-model="formData.orderGoodPoList[index].buyNum"
                style="width: 110px"
                label="请输入数量"
              >
                <template slot="append">份</template></el-input
              >
            </el-form-item>
            <el-button
              @click="removeProduct(product)"
              v-if="formData.orderGoodPoList.length > 1"
              >删除</el-button
            >
          </div>
          <el-button
            style="width: 100%"
            icon="el-icon-plus"
            @click="addOrderGood"
            >添加商品</el-button
          >
        </div>
      </el-form-item>

      <el-form-item
        label="商品总额"
        prop="totalPrice"
        :rules="[
          {
            required: true,
            message: '请选择商品',
            trigger: 'blur',
          },
        ]"
      >
        {{ formData.totalPrice ? `${formData.totalPrice}(元)` : "-" }}
      </el-form-item>

      <el-form-item
        label="折扣"
        prop="discountRatio"
        :rules="[
          {
            required: true,
            message: '请选择商品',
            trigger: 'blur',
          },
        ]"
      >
        <el-slider v-model="formData.discountRatio"></el-slider>
      </el-form-item>

      <el-form-item
        label="订单金额"
        prop="orderPrice"
        :rules="[
          {
            required: true,
            message: '请选择商品',
            trigger: 'blur',
          },
        ]"
      >
        {{ formData.orderPrice ? `${formData.orderPrice}(元)` : "-" }}
      </el-form-item>

      <el-form-item label="取鞋日期" prop="orderPrice">
        <el-date-picker
          v-model="formData.shoeCollectionDate"
          type="date"
          :picker-options="pickerOptions"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item
        label="鞋子数量"
        prop="shoesNum"
        :rules="[
          {
            required: true,
            message: '请输入鞋子数量',
            trigger: 'blur',
          },
          {
            pattern: /^[1-9]\d*$/,
            message: '请输入正确的数字',
            trigger: 'blur',
          },
        ]"
      >
        <el-input
          placeholder="请输入鞋子数量"
          v-model="formData.shoesNum"
        ></el-input>
      </el-form-item>

      <el-form-item prop="customerRemark" label="客户备注">
        <el-input
          type="textarea"
          placeholder="请输入客户备注"
          v-model="formData.customerRemark"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm('formData')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>

    <el-dialog
      custom-class="order-create-dialog"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div style="text-align: center">
        <div>
          <i style="color: #67c23a; font-size: 50px" class="el-icon-success" />
        </div>
        <h1>订单提交成功</h1>
        <p>可前往“订单详情”查看订单水洗码详情，并打印水洗码。</p>
      </div>
      <div slot="footer" style="text-align: center">
        <el-button @click="toDetail">订单详情</el-button>
        <el-button type="primary" @click="printReceipt">打印小票</el-button>
      </div>
    </el-dialog>

    <PrintOrderReceipt
      :detail="printOrderReceiptObject.detail"
      :shopName="printOrderReceiptObject.shopName"
      :id="printOrderReceiptObject.id"
      :productListMap="productListMap"
      ref="PrintOrderReceipt"
    />
  </div>
</template>

<script>
import { getShopGoods } from "@/api/product/index";
import { createOrder } from "@/api/order/index";
import { washTypeList } from "@/config/index";
import PrintOrderReceipt from "@/components/PrintOrderReceipt/PrintOrderReceipt";
export default {
  components: {
    PrintOrderReceipt,
  },
  data() {
    return {
      formData: {
        orderGoodPoList: [
          {
            goodsId: "",
            buyNum: "1",
          },
        ],
        shoeCollectionDate: "",
        customPhone: "",
        discountRatio: 100,
        customerRemark: "",
        shoesNum: "",

        orderPrice: "",
        totalPrice: "",
      },
      dialogVisible: false,
      productList: [],
      washTypeList,

      pickerOptions: {
        disabledDate: (time) => {
          return time.getTime() <= Date.now();
        },
      },

      productListMap: {},

      printOrderReceiptObject: {
        detail: "",
        shopName: "",
        id: "list-print",
      },
    };
  },
  created() {
    this.getProductList();
  },
  watch: {
    "formData.orderGoodPoList": {
      handler: function (val) {
        let totalPrice = 0;
        let shoesNum = 0;
        val.forEach((item) => {
          const product = this.productList.find((p) => p.id === item.goodsId);
          if (product) {
            totalPrice += product.price * (item.buyNum || 0);
            shoesNum += (item.buyNum || 0) * product.shoesNum;
          }
        });

        // 计算鞋子数量
        this.formData.shoesNum = shoesNum;

        if (totalPrice.toString === "NaN") {
          this.formData.totalPrice = "";
          this.formData.orderPrice = "";
          return;
        }

        this.formData.totalPrice = totalPrice.toFixed(2);
        this.formData.orderPrice = (
          totalPrice *
          (this.formData.discountRatio / 100)
        ).toFixed(2);
      },
      deep: true,
    },
    "formData.discountRatio": {
      handler: function (val) {
        this.formData.orderPrice = (
          this.formData.totalPrice *
          (val / 100)
        ).toFixed(2);
      },
    },
  },
  methods: {
    getProductList() {
      getShopGoods(
        {
          extendInfo: "abc",
        },
        1,
        999999
      ).then((res) => {
        this.productList = res.data.records;
        let productListMap = {};
        res.data.records.forEach((item) => {
          productListMap[item.id] = item;
        });
        this.productListMap = productListMap;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const params = {
            ...this.formData,
            comeFrom: 1,
            shoeCollectionDate: this.formData.shoeCollectionDate
              ? this.formData.shoeCollectionDate.getTime()
              : "",
            shopId: this.$store.state.user.currentShop.id,
          };
          createOrder(params).then((res) => {
            this.detail = res.data;
            this.dialogVisible = true;
          });
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },
    addOrderGood() {
      this.formData.orderGoodPoList.push({
        goodsId: "",
        buyNum: "1",
        key: Date.now(),
      });
    },
    removeProduct(item) {
      var index = this.formData.orderGoodPoList.indexOf(item);
      if (index !== -1) {
        this.formData.orderGoodPoList.splice(index, 1);
      }
    },
    toDetail() {
      this.$router.push({ path: "/order/list", query: { id: this.detail.id } });
    },
    cancel() {
      this.$router.push({ path: "/order/list" });
    },
    printReceipt() {
      this.printOrderReceiptObject = {
        detail: this.detail,
        shopName: this.$store.state.user.currentShop.shopName,
        id: "list-print",
      };

      this.$nextTick(() => {
        this.$refs.PrintOrderReceipt.$refs.printBtn.click();
      });
    },
  },
};
</script>

<style lang="scss">
.order-create-form {
  width: 800px;
  .choose-product {
    display: flex;
    margin-bottom: 20px;
    & > * {
      margin-right: 10px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.order-create-dialog {
  .el-dialog__header {
    padding: 0;
  }
}
</style>
